﻿package bdz.projects.lavender.doi.ui
{
	import bdz.common.display.DisplayLoader;
	import bdz.common.managers.AudioControlManager;
	import bdz.common.events.*;
	import bdz.projects.lavender.doi.utils.CuePointManager;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.filters.GlowFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.*;
	import gs.easing.*;
	import gs.*;
	/**
	 * ...
	 * @author ...
	 */
	public class DOIStepAnimation extends MovieClip 
	{
		private var cpm:CuePointManager = CuePointManager.getInstance();
		
		private var screenHolder:MovieClip;
		private var screenLoader:DisplayLoader;
		private var audioManager:AudioControlManager;
		
		private var masker:MovieClip;
		private var _maskdimension:Object;
		private var _imgsource:String;
		private var _audiosource:String;
		private var _def:XML;
		private var _imgLoaded:Boolean = false;
		private var _audioLoaded:Boolean = false;
		private var elements:Array;
		private var dimmer:MovieClip;
		private var elementsDict:Dictionary;
		private var lastaudiomatch:String;
		private var resetmatch:Number;
		function DOIStepAnimation(img:String, vo:String, def:XML, maskdim:Object):void {
			_imgsource = img;
			_audiosource = vo;
			_def = def;
			trace(_imgsource);
			_maskdimension = maskdim;
			
			initializeComponent();
			addEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
		}
		private function initializeComponent(evt:Event = null):void {
			screenHolder = new MovieClip();
			addChild(screenHolder);
			
			screenLoader = new DisplayLoader();
			screenHolder.addChild(screenLoader);
			
			screenLoader.addEventListener(Event.COMPLETE, onImageLoaded);
			audioManager = new AudioControlManager();			
			audioManager.addEventListener(GenericEvent.COMPLETE, onAudioLoaded);
			audioManager.addEventListener(GenericEvent.PROGRESS, onAudioPlayProgress);
			audioManager.addEventListener(GenericEvent.PROGRESS_COMPLETE, onAudioProgressComplete);
			audioManager.refreshRate = 100;
			
			
			screenLoader.source = _imgsource;
			
			convertDefinitionToArray(_def);
			attachUIElements();
			createMasker();
		}
		private function createDimmer():void {
			try {
				screenHolder.removeChild(dimmer);
			}catch (e:Error) { };
			dimmer = new screenDimmer();
			dimmer.width = _maskdimension.width;
			dimmer.height = _maskdimension.height;
			screenHolder.addChild(dimmer);
		}
		private function createMasker():void {
			masker = new MovieClip();
			masker.graphics.beginFill(0x000000, 0);
			masker.graphics.drawRect(0, 0, _maskdimension.width, _maskdimension.height);
			masker.graphics.endFill();
			addChild(masker);
			screenHolder.mask = masker;
		}
		private function highlightElement(hl:MovieClip, w:Number):void {
			dimmer.gotoAndPlay(2);
			TweenLite.to(hl, .6, {delay:.1, width:w, ease:Strong.easeInOut, onComplete:removeHighlights, onCompleteParams:[hl] } );
		}
		private function removeHighlights(hl:MovieClip):void {
			TweenLite.to(dimmer, 1, { delay:2, alpha:0, ease:Strong.easeInOut } );
			TweenLite.to(hl, 1, {delay:2, scaleX:0, ease:Strong.easeInOut } );
		}
		private function tweenBack(targ):void {
			TweenMax.to(targ, .6, { scaleX:1, scaleY:1, ease:Strong.easeInOut } );
			TweenMax.to(dimmer, .6, {alpha:0, ease:Strong.easeInOut, onComplete:screenHolder.removeChild, onCompleteParams:[dimmer]});
		}
		private function createHighlight(targ):void {
			
			
			createDimmer();
			var hl:MovieClip = new highlighter();
			hl.x = Math.ceil(Number(targ.containerx) + Number(targ.elementx))-10;
			hl.y = Math.ceil(Number(targ.containery) + Number(targ.elementy)) - 10;
			hl.width = 0;
			hl.height = targ.flashui.bui.height + 20;
			hl.scaleX = 0;
			var glw:GlowFilter = new GlowFilter(0xffffff, 1, 52, 52, 2, 3);
			hl.filters = [glw];
			screenHolder.addChild(hl);
			screenHolder.setChildIndex(targ.flashui, screenHolder.numChildren - 1);
			highlightElement(hl, targ.flashui.bui.width+20);
			
		}
		
		private function animateElement(ele:Object):void {
			var targ:* = elementsDict[ele.mx_internal_uid];
			createHighlight(targ);
		}
		private function getMinSec(tme:Number):Object {
			var secs:* = Math.floor(tme/1000);
			var mins:* = Math.floor(secs/60);
			secs %= 60;
			mins %= 60;
			if(secs < 10){
				secs = "0"+secs;
			}
			if(mins < 10){
				mins = "0"+mins;
			}
			return {secs:secs,mins:mins};
		}
		private function resetLastMatch():void {
			lastaudiomatch = "";
		}
		private function compareTimeString(n1:Number, n2:Number):Boolean {
			var timeString1:String = getMinSec(n1).mins + ":" + getMinSec(n1).secs;
			var timeString2:String = getMinSec(n2).mins + ":" + getMinSec(n2).secs;
			if (timeString1 == timeString2) {
				if (lastaudiomatch != timeString1 && lastaudiomatch != timeString2) {
					lastaudiomatch = timeString1;
					
					return true;
				}
			}
			return false;
		}
		private function attachUIElements():void {
			elementsDict = new Dictionary();
			for each(var ele:* in elements) {
				var uicoords:Object = {x:Number(ele.containerx), y:Number(ele.containery)}
				var elcoords:Object = {x:Number(ele.elementx), y:Number(ele.elementy)}
				var dim:Object = { width:Number(ele.compwidth), height:Number(ele.compheight) };
				elementsDict[ele.mx_internal_uid] = ele;
				elementsDict[ele.mx_internal_uid].flashui = createElement(ele.classname,ele.uilabel, uicoords, elcoords, dim, ele.raw);
			}
		}
		private function createElement(oclass:String, olabel:String, ocoords:Object, ecoords:Object, odimension:Object, raw:XML):* {
			var ui:* = getDefinitionByName(oclass);
			if(ui){
				var baseui = new ui();
				screenHolder.addChild(baseui);
				if (oclass == "FLTextInput") {
					
				}else{
					baseui.setValues(raw);
				}
				baseui.uibg.visible = false;
				baseui.forceDimension(ecoords, odimension);
				baseui.x = ocoords.x;
				baseui.y = ocoords.y;
				baseui.disableControls();
				return baseui;
			}
			return null;
		}
		private function convertDefinitionToArray(xm:XML):void {
			elements = new Array();
			var els:XMLList = xm.element;
			for each(var xels:XML in els) {
				var ele:Object = convertElementToObject(xels);
				elements.push(ele);
			}
		}
		private function convertElementToObject(xm:XML):Object {
			var ret:Object = { };
			var chl:XMLList = xm.children();
			for each(var c:XML in chl) {
				ret[c.name()] = c.toString();
			}
			
			ret.raw = xm;
			return ret;
		}
		private function onAudioProgressComplete(evt:GenericEvent):void {
			trace("finished playing");
		}
		private function onAudioPlayProgress(evt:GenericEvent):void {
			for each(var ele:Object in elements) {
				if (compareTimeString(Number(ele.rmarkertime), Number(evt.data.position))) {
					animateElement(ele);
				}
			}
		}
		private function onAudioLoaded(evt:GenericEvent):void {
			_audioLoaded = true;
		}
		private function onImageLoaded(evt:Event):void {
			
			_imgLoaded = true;
			audioManager.autoPlay = true;
			audioManager.source = _audiosource;
		}
		public function refreshContent(img:String, vo:String, def:XML, maskdim:Object):void {
			cleanUp();
			_imgsource = img;
			_audiosource = vo;
			_def = def;
			_maskdimension = maskdim;
			initializeComponent();
		}
		public function cleanUp(evt:Event = null):void {
			
			try {
				screenLoader.cleanUp();
			}catch (e:Error) { };
			try {
				audioManager.clear();
			}catch (e:Error) { };
			try {
				removeChild(screenHolder);
			}catch (e:Error) { };
		}
		
	}
	
}